import { EventSourceMessage, fetchEventSource } from '@microsoft/fetch-event-source';

import { useUserStore } from '@/store';

const url = `${import.meta.env.VITE_API_URL}${import.meta.env.VITE_API_URL_PREFIX}/ai/chat/message/send-stream`;

export default ({
  body,
  signal,
  onMessage,
  onError,
  onClose,
}: {
  body: Record<string, any>;
  signal: AbortSignal;
  onMessage: (ev: EventSourceMessage) => void;
  onError: (err: any) => number | null | undefined | void;
  onClose: () => void;
}) => {
  const userStore = useUserStore();

  return fetchEventSource(url, {
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${userStore.token}`,
    },
    openWhenHidden: true,
    body: JSON.stringify(body),
    signal,
    onmessage: onMessage,
    onerror: onError,
    onclose: onClose,
  });
};
